package com.example.rabbit.seven;

import com.example.rabbit.util.RabbitMqUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * topic主题订阅模式
 *
 * @Author ifredomvip@gmail.com
 * @Date 2022/8/8 17:28
 * @Version 1.0.0
 * @Description
 **/
public class ReceiveTopic01 {
    public static String exchangeName = "Topic-logs";
    public static String routingKey = "*.orange.*";// 一共三个单词，中间单词为orange的匹配
    public static String queueName = "Q1";

    public static void main(String[] args) {
        try {
            Channel channel = RabbitMqUtils.getChannel();
            //交换机声明（参数为：交换机名称；交换机类型）
            channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC);

            channel.queueDeclare(queueName, false, false, false, null);
            channel.queueBind(queueName, exchangeName, routingKey);

            System.out.println("ReceiveTopic01 等待消息接收，把接收消息打印在屏幕上");

            DeliverCallback deliverCallback = (consumeTag, deliver) -> {
                String message = new String(deliver.getBody(), StandardCharsets.UTF_8);

                System.out.println(queueName + "收到的消息:" + message);
            };

            channel.basicConsume(queueName, true, deliverCallback, (consumeTag) -> {
            });
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
